package cmsapi

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"oxy_server/module/log"

	// "net/http"
	"github.com/labstack/echo"
	// "github.com/labstack/echo/middleware"
)

func Upload(c echo.Context) error {
	// Read form fields
	name := c.FormValue("productid")

	//-----------
	// Read file
	//-----------
	// Source
	_dir := "/picdata/" + name
	exist, err := PathExists(_dir)
	if err != nil {
		fmt.Printf("get dir error![%v]\n", err)
		return err
	}

	if exist {
		fmt.Printf("has dir![%v]\n", _dir)
	} else {
		fmt.Printf("no dir![%v]\n", _dir)
		// 创建文件夹
		err := os.Mkdir(_dir, os.ModePerm)
		if err != nil {
			fmt.Printf("mkdir failed![%v]\n", err)
		} else {
			fmt.Printf("mkdir success!\n")
		}
	}

	file, err := c.FormFile("file")
	if err != nil {
		return err
	}
	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	// Destination
	dst, err := os.Create(_dir + "/" + file.Filename)
	if err != nil {
		return err
	}
	defer dst.Close()
	contentByte, err := ioutil.ReadAll(dst)
	if err != nil {
		fmt.Println("read file err")
		return err
	}
	_, err = dst.Write(contentByte)
	if err != nil {
		fmt.Println("Write file err")
		return err
	}
	// Copy
	if _, err = io.Copy(dst, src); err != nil {
		return err
	}
	p := map[string]interface{}{
		"文件地址": string(name + "/" + file.Filename),
	}
	s, err := json.Marshal(p)
	bufbody := bytes.NewBuffer(s)
	c.Request().Body = ioutil.NopCloser(bufbody)

	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": string(name + "/" + file.Filename),
	})
	return nil
}

func DelFile(c echo.Context) error {
	filepath := c.QueryParam("filepath")
	log.Info("删除文件", filepath)
	err := os.Remove(filepath)
	if err != nil {
		log.Error("删除失败", err)
		c.JSON(200, map[string]interface{}{
			"msg": "文件不存在",
		})
		return err
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})
	return nil
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
